<?php
namespace Common\Wechat;
use Exception;
class WxAccess{
	// 返回微信AccessToken
	function WxAccessToken()
	{
		// 如果token的获取时间小于2小时就返回
		$data = S('wxAccessToken');
		if ( $data && $data['gettime'] > strtotime('-2 hours') ) {
			return $data['access_token'];
		}
		
		// 获取token
		$wx_appId = C('wx_appId');
		$wx_appSecret = C('wx_appSecret');
		$urlParameter = array(
			'grant_type' => 'client_credential',
			'appid' => C('wx_appId'),
			'secret' => C('wx_appSecret')
		);
		$url = 'https://api.weixin.qq.com/cgi-bin/token?'.http_build_query($urlParameter);
		$result = file_get_contents($url);
		$result = json_decode($result, true);
		if ( isset($result['errcode'])) {
			throw new Exception("调用微信接口凭证失败！");
		}
		// 缓存数据2小时
		$data = array(
			'access_token' => $result['access_token'],
			'gettime' => time()
		);
		S('wxAccessToken', $data, 10);
		return $data['access_token'];
	}
}